# @Time   : 2022-03-03 17:00:00
# @Author : Gavin Jiang
# @Owner  : YSRD (Insights Value)

import json
from datetime import date, datetime
from decimal import Decimal
# import demjson
from sqlalchemy.ext.declarative import DeclarativeMeta

from framework.vo.view_object import ViewObject


class RequestJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        # sl加对model对象的转换
        if isinstance(obj.__class__, DeclarativeMeta):

            fields = {}
            for field in [x for x in dir(obj) if
                          not x.startswith('_') and x != 'metadata' and x != 'query' and x != 'query_class']:
                data = obj.__getattribute__(field)
                try:
                    if data is None:
                        fields[field] = ''
                    elif isinstance(data, ViewObject):
                        # json.dumps(data,cls=ComplexEncoder)
                        fields[field] = json.dumps(data, ensure_ascii=False, cls=RequestJsonEncoder)
                        # fields[field] =json.dumps(data, default=lambda obj: obj.__dict__)
                    else:
                        fields[field] = data

                except TypeError:
                    fields[field] = data
            return fields
        # sl加对普通对象的转换
        # 因为demjson的安装经常会失败，默认关闭demjson功能，有需要的子系统可以自行开启
        # elif isinstance(obj, ViewObject):
        #     return demjson.decode(json.dumps(obj, ensure_ascii=False, default=lambda obj1: obj1.__dict__))
        elif isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, Decimal):
            return str(obj)
        else:
            return json.JSONEncoder.default(self, obj)
